import type mapboxgl from 'mapbox-gl'
import { type SymbolStyle, addLayer, registerMapLegend, BaseSymbolLayer } from '@/map'
import type { Waypoint } from './types'
import { waypoint2Feature } from './feature'

// 航路点样式
const waypointStyle: SymbolStyle = {
  icon: 'waypoint-8',
  color: '#CDCADA',
  textOpacity: 1.0,
  fontScale: 0.8,
  textOffset: [0, -0.6]
}

export let waypointLayer: BaseSymbolLayer<Waypoint>

function initWaypointLayer(lst: Waypoint[]) {
  const opts = {
    id: 'Entity:Waypoint',
    name: '航路点',
    getFeature: (wpt: Waypoint) => waypoint2Feature(wpt, { text: wpt.id }),
    style: waypointStyle,
    textField: ['get', 'text'] as mapboxgl.Expression,
    minZoom: 4.9
  }
  const layer = new BaseSymbolLayer<Waypoint>(opts, lst)
  waypointLayer = layer
  addLayer(layer)
}

function initWaypointLayerLegend() {
  registerMapLegend({
    name: '航路点',
    visible() {
      return waypointLayer.visible
    },
    setVisible(ok) {
      waypointLayer.visible = ok
    }
  })
}

export function initMap(wptLst: Waypoint[]) {
  initWaypointLayer(wptLst)
  initWaypointLayerLegend()
}
